<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\RoleModel;
use app\model\AuthRuleModel;
use app\server\Redis;

class CheckAuth
{
    /**
     * 仅验证角色和权限
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $nowUrl=nowUrl($request);
        $master = $request->master;
        //验证权限
        $role = RoleModel::where('id', $master['rid'])->find();
        if (empty($role)) {
            return error('角色不存在',402);
        }
        if ($role['status'] == 0) {
            return error('角色被禁用',402);
        }
        //从redis获取全部正常状态的规则列表
        $redis=new Redis();
        $authRuleRedis=$redis->getAuthRule();
        if($authRuleRedis!==false&&!empty($authRuleRedis)){
            $authRule=json_decode($authRuleRedis,true);
        }else{
            $authRule = AuthRuleModel::where('status', 1)->select()->toArray();
            $redis->setAuthRule(json_encode($authRule));
        }
        //登录信息中加入权限ids
        $master['rule_id'] = $role['rule_id'];
        $request->master = $master;
        //从列表中根据数据id筛选出当前用户的权限路由
        $authRuleUser=arrayInModel('id',$role['rule_id'],$authRule);
        //遍历路由得到路由地址
        $authRuleNames=array_column($authRuleUser,'name');
        //将路由地址与当前路由做匹配
        if (!in_array('/' . $nowUrl['module'] . '/' . $nowUrl['controller'] . '/' . $nowUrl['action'], $authRuleNames)) {
            return error('您没有权限',402);
        }
        return $next($request);
    }
}
